import { useForm } from '@formily/react';
import { useQueryFields } from '@inbiz/hooks';
import { Empty, Input, message, Select } from 'antd';
import { useEffect, useState, useRef } from 'react';
import { request } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';

// type IProps = {
//   callBackEvents?: { [key: `on${string}`]: Function }
//   emit?: (type: any, ...arg: any) => void
// } & typeof defaultProps
const { Option } = Select;

type IPorps = {
  valueType?: 'value' | 'origin_FieldName';
  update: string;
  onChange: (value: string) => void;
  value?: string;
  syncModel?: string;
};
type IOptions = {
  value: string;
  label: string;
};
const MyAutoComplete = (props: IPorps) => {
  // 准备数据
  const form = useForm();
  const sourceModel = form.query('form.senior.soure.x-component-props.sourceModel').take()! as {
    value: string;
  };

  const [options, setOptions] = useState<IOptions[]>([]);

  const asyncLoading = useRef(false);
  // result[0]：所有字段
  // result[1]: 是否还在加载  true为正在加载  false为加载完成
  const [fieldList, loadding] = useQueryFields(
    {
      key: typeof sourceModel?.value === 'string' ? sourceModel?.value : sourceModel?.value?.searchData,
      //@ts-ignore
      appId: form.appInfo.appId,
    },
    [props.update],
  );

  useEffect(() => {
    if (!fieldList?.length || props.syncModel) {
      return;
    }
    let nowOptions: IOptions[] = [];
    fieldList.forEach((item: any) => {
      nowOptions.push({ value: item[props.valueType || 'origin_FieldName'], label: item.label });
    });
    setOptions(nowOptions);
  }, [loadding]);

  const getSyncOpton = async () => {
    asyncLoading.current = true;
    const res = await request(
      `/inbiz/api/services/modelengine/v${InbizConfig.API_VERSION}/model/fieldByModelName?name=${props.syncModel}`,
    );
    asyncLoading.current = false;
    if (res) {
      setOptions(res.map((ele: any) => ({ value: ele.Name, label: ele.Name })));
    }
  };

  useEffect(() => {
    if (props.syncModel) {
      getSyncOpton();
    }
  }, [props.syncModel]);

  const onFocus = () => {
    if (!loadding && options?.length < 1 && !asyncLoading.current) {
      message.warning(getMessage('EformInput.tips.pleaseSetQuerySource'));
    }
  };
  if (sourceModel?.value === undefined) {
    return <Input {...props} onChange={e => props.onChange(e.target.value)} />
  }

  return (
    <Select
      {...props}
      allowClear
      showSearch
      onFocus={onFocus}
      value={options.length === 0 ? undefined : props.value}
      notFoundContent={
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description={<TextWidget>pageselect.no_data</TextWidget>}
        />
      }
    >
      {options.map((item: any, i) => {
        return (
          <Option value={item.value} key={i}>
            {item.label}
          </Option>
        );
      })}
    </Select>
  );
};

export default MyAutoComplete;
